<template>
  <div>
    <BasicTable @register="registerTable" ref="tableRef">
    </BasicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { onMounted, ref, unref } from 'vue'
  import { BasicTable, useTable, FormSchema, TableActionType } from '@/components/Table';
  import { getMeDataList } from '@/api/datacenter';
  import { getEntityList } from '@/api/entity';
  import { type Nullable } from '@vben/types';

  const entityOptions = ref([]);
  const entityFieldsMap = ref({});
  const tableRef = ref<Nullable<TableActionType>>(null);

  onMounted(() => {
    loadEntityList();
  });

  const searchFormSchemas: FormSchema[] = [
    {
      field: 'entity_id',
      label: '实体',
      component: 'Select',
      componentProps: {
        options: entityOptions,
        onChange: (e) => {
          const tableAction = unref(tableRef);
          tableAction.setProps({
            api: getMeDataList,
            columns: entityFieldsMap.value[e],
          });
        },
      },
      colProps: { span: 8 },
    },
  ];

  const [registerTable, { reload }] = useTable({
    api: '',
    columns: [],
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchemas,
    },
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
  });

  const loadEntityList = async () => {
    const items = (await getEntityList()).items;
    const options: any = [];
    for (const item of items) {
      options.push({
        label: item.name,
        key: items.id,
        value: item.id,
      });
      const fields: any[] = [];
      for (const field of item.fields) {
        const fieldItem = {
          title: field.label? field.label: field.field,
          dataIndex: field.field,
        }
        fields.push(fieldItem);
      }
      entityFieldsMap.value[item.id] = fields;
    }
    entityOptions.value = options;
  };

</script>